package com.authentications.security;

import com.authentications.security.info.UserPasswordInfo;
import com.authentications.security.password.UserPassword;
import com.authentications.utils.SpringContextUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName DefaultUserDetailsService
 * @Author xiezhuocai
 * @Description 统一处理用户信息
 * @Date 2021/12/19 23:25
 */
@Configuration
public class DefaultUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //组装用户信息和权限
        UserPassword beansOfType = SpringContextUtils.getBean(UserPassword.class);
        UserPasswordInfo pwd = beansOfType.pwd(username);
        //if (pwd.getRoles() == null) pwd.setRoles("admin");//ROLE_
        List<String> roles = pwd.getRoles();
        List<String> authorities = pwd.getAuthorities();
        if (roles!=null&&!roles.isEmpty()){
            for (String role : roles) {
                authorities.add("ROLE_" + role);
            }
        }
        UserDetails userDetails = User
                .withUsername(pwd.getUserInfo())
                .password(pwd.getPwd())
                .authorities(authorities.toArray(new String[authorities.size()]))
                .build();
        return userDetails;
    }
}
